package com.excesys.exsecs.linkage.alarm;

import com.excesys.exsecs.linkage.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Component
public class TencentEnterpriseEmailSender {
	@Autowired
	private  SmsConfig smsConfig;


    public String sendMsg(String recipientEmail,String body) {
        // 收件人邮箱账号  recipientEmail
		// 邮件正文内容  body
		// 发件人腾讯企业邮箱账号
		String senderEmail = smsConfig.getSenderEmail();
		// 腾讯企业邮箱授权码（通过邮箱设置获取，不是登录密码）
		String senderPassword = smsConfig.getSenderPassword();
        // 邮件主题
        String subject = "告警邮件";
        // 设置邮件服务器相关属性
        Properties properties = new Properties();
        // 腾讯企业邮箱SMTP服务器主机名
        properties.put("mail.smtp.host", "smtp.exmail.qq.com");
        // 腾讯企业邮箱SMTP服务器端口号
        properties.put("mail.smtp.port", "465");
        // 设置是否需要认证
        properties.put("mail.smtp.auth", "true");
        // 设置启用SSL加密（腾讯企业邮箱常用的安全连接方式）
        properties.put("mail.smtp.ssl.enable", "true");
        // 启用JavaMail调试模式
        properties.put("mail.debug", "true");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // 创建会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        });

        try {
            // 创建邮件消息对象
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(senderEmail));
            // 设置收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
            // 设置邮件主题
            message.setSubject(subject);
            // 设置邮件正文内容
            message.setText(body);

            // 发送邮件
            Transport.send(message);
            return ("邮件发送成功！");
        } catch (MessagingException e) {
            e.printStackTrace();
			return("邮件发送失败：" + e.getMessage());
        }
	}
}